package helm

import (
	"fmt"
	"github.com/pkg/errors"
	"helm.sh/helm/v3/pkg/helmpath"
	"helm.sh/helm/v3/pkg/repo"
	"os"
	"path/filepath"
)

func BuildIndex(helmRepo, helmCache string) (*Index, error) {
	// Load the repositories.yaml
	rf, err := repo.LoadFile(helmRepo)
	if isNotExist(err) || len(rf.Repositories) == 0 {
		return nil, errors.New("no repositories configured")
	}

	i := NewIndex()
	for _, re := range rf.Repositories {
		n := re.Name
		f := filepath.Join(helmCache, helmpath.CacheIndexFile(n))
		ind, err := repo.LoadIndexFile(f)
		if err != nil {
			fmt.Printf("Repo %q is corrupt or missing. Try 'helm-srv repo update'.", n)
			fmt.Printf("%s", err)
			continue
		}

		i.AddRepo(n, ind, false)
	}
	return i, nil
}

func isNotExist(err error) bool {
	return os.IsNotExist(errors.Cause(err))
}
